package generics;

import utils.PrintlnUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class JavaBaseUser<T extends JavaAnimal> {
    private T mAnimal;

    public JavaBaseUser() {
//        Class<T> type1 = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
//        try {
//            mAnimal = type1.newInstance();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }

        Type getGenericSuperclass = this.getClass().getGenericSuperclass();
        if (getGenericSuperclass != null && getGenericSuperclass instanceof ParameterizedType) {
            Class<T> type = (Class<T>) ((ParameterizedType) getGenericSuperclass).getActualTypeArguments()[0];
            try {
                mAnimal = type.newInstance();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                PrintlnUtils.println(this.getClass().getSimpleName() + " , mAnimal 异常信息：" + e.toString());
            } catch (InstantiationException e) {
                e.printStackTrace();
                PrintlnUtils.println(this.getClass().getSimpleName() + " , mAnimal 异常信息：" + e.toString());
            }

        }

        if (getGenericSuperclass == null) {
            PrintlnUtils.println("JavaBaseUser  getGenericSuperclass== null");

        } else if (!(getGenericSuperclass instanceof ParameterizedType)) {
            PrintlnUtils.println("JavaBaseUser  getGenericSuperclass 不是 ParameterizedType , getSimpleName: " + getGenericSuperclass.getClass().getSimpleName() + " , getTypeName: " + getGenericSuperclass.getTypeName());

        }
    }

    public void setAnimalInfo(String parmName, int parmAge) {
        if (mAnimal == null) {
            PrintlnUtils.println("setAnimalInfo mAnimal == null ， 设置失败");
            return;
        }

        mAnimal.setName(parmName);
        mAnimal.setAge(parmAge);
    }


    public void printAnimalInfo() {
        if (mAnimal == null) {
            PrintlnUtils.println(this.getClass().getSimpleName() +" , printAnimalInfo mAnimal == null ， 打印失败");
            return;
        }

        PrintlnUtils.println(this.getClass().getSimpleName() + " , printAnimalInfo mAnimal getName = " + mAnimal.getName() + " , getAge() = " + mAnimal.getAge());
    }


}
